﻿using PLC.Interface.Groups;
using PLCWpfTest.Common;
using PLCWpfTest.Models;
using System.Threading.Tasks;
using YWM.Common.Exceptions;
using YWM.Dto;

namespace PLCWpfTest.ViewModels
{
    public class GroupOperationViewModel : OperationViewModel
    {
        public NameValueModel<byte>[] StoreAreas { get; set; }

        private readonly IGroupAppService _groupAppService;

        public GroupDto Group { get; set; } = new GroupDto();

        public GroupOperationViewModel(IGroupAppService groupAppService, GroupDto group)
        {
            StoreAreas = new NameValueModel<byte>[] {
                new NameValueModel<byte>(Lang["线圈状态"], 0),
                new NameValueModel<byte>(Lang["输入状态"], 1),
                new NameValueModel<byte>(Lang["保持寄存器"], 2),
                new NameValueModel<byte>(Lang["输入寄存器"], 3)
            };

            _groupAppService = groupAppService;

            if (group != null)
            {
                Group = group;
                IsAdd = false;
            }
        }

        protected override bool OkCommand_BeforeCanExecute(object parameter)
        {
            return Group.IsValidated;
        }

        protected override async Task<IEntityDto> OkAsync(object parameter)
        {
            Group.Error = string.Empty;
            GroupResultDto group = await _groupAppService.Save(Group);
            CommunicationCache.Groups = await _groupAppService.GetList(true);
            RaiseRequestClose();
            return group;
        }

        protected override void OkCommand_UnexecutedFriendlyException(FriendlyException ex)
        {
            Group.Error = ex.Message;
        }
    }
}
